package com.mjk.common.util;

import com.mjk.common.tools.logger.BizLogger;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 给图片添加文字水印
 * 
 * @author mjk
 * @date 2019年1月16日
 */
@Slf4j
public class ImgWaterUtil {

	// 水印文字大小
	public static final int FONT_SIZE = 70;
	// 水印文字字体
	private static final Font font = new Font("仿宋体", Font.BOLD, FONT_SIZE);
	// 水印文字颜色
	private static final Color color = Color.lightGray;
	// 水印之间的间隔
	private static final int XMOVE = 20;
	// 水印之间的间隔
	private static final int YMOVE = 20;

	private  ImgWaterUtil() {}


	/**
	 * 给图片添加水印文字、可设置水印文字的旋转角度
	 *
	 * @param waterText  待设置的水印文字
	 * @param srcImgPath 源文件路径
	 * @param targetPath 目标文件路径
	 * @param degree     旋转度
	 */
	public static void addImageWaterMark(String waterText, String srcImgPath, String targetPath, Integer degree) {
	
		boolean srcExists = Files.exists(Paths.get(srcImgPath));

		if (!srcExists) {
			BizLogger.warn("addImageWaterMark src="+srcImgPath+" not exists");
			return;
		}
		long start = System.currentTimeMillis();
		//InputStream is = null;

		try (OutputStream os = new FileOutputStream(targetPath);){
			// 源图片
			Image srcImg = ImageIO.read(new File(srcImgPath));
			int width = srcImg.getWidth(null);// 原图宽度
			int height = srcImg.getHeight(null);// 原图高度
			BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
					BufferedImage.TYPE_INT_RGB);
			// 得到画笔对象
			Graphics2D g = buffImg.createGraphics();
			// 设置对线段的锯齿状边缘处理
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0,
					0, null);
			// 设置水印旋转
			if (null != degree) {
				g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
			}
			// 设置水印文字颜色
			g.setColor(color);
			// 设置水印文字Font
			g.setFont(font);
			// 设置水印文字透明度
			// 水印透明度
			float alpha = 0.4f;
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

			int x = -width / 2;
			int y;
			int markWidth = FONT_SIZE * StrUtils.getTextLength(waterText);// 字体长度

            // 循环添加水印
			while (x < width * 1.5) {
				y = -height / 2;
				while (y < height * 1.5) {
					g.drawString(waterText, x, y);
					y += FONT_SIZE + YMOVE;
				}
				x += markWidth + XMOVE;
			}
			// 释放资源
			g.dispose();
			ImageIO.write(buffImg, "JPG", os);
			long end = System.currentTimeMillis();
			BizLogger.debug("addWaterMark cost time={}", end - start);
		} catch (Exception e) {
			BizLogger.error("addWaterMark error", e);
		}

	}

}
